/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: DealPriceFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.kline.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.utils.KlineUtils;
import io.bhex.app.view.MyLinearLayoutManager;
import io.bhex.app.view.WrapContentHeightViewPager;
import io.bhex.baselib.constant.AppData;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.DealPriceBean;
import io.bhex.app.kline.presenter.DealPriceFragmentPresenter;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.app.utils.DateUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.baselib.utils.DebugLog;

/**
 * ================================================
 * 描   述：最新成交
 * ================================================
 */

public class DealPriceFragment extends BaseFragment<DealPriceFragmentPresenter, DealPriceFragmentPresenter.DealPriceUI> implements DealPriceFragmentPresenter.DealPriceUI, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {
    private static final String TAG = "DealPriceFragment";
    private SwipeRefreshLayout swipeRefresh;
    private static final int REFRESH_DATA = 0;
    private RecyclerView recyclerView;
    private DealPriceAdapter adapter;
    private String exchangeId="";
    private CoinPairBean coinPairBean;
    private String symbol="";
    private String baseToken;
    private String quoteToken;
    private String mergeDigitsStr;
    private String basePrecision;
    private String quotePrecision;
    private int digitBase;
    private int digitQuote;
    private long lastUpdateTime;
    private List<DealPriceBean.DealItem> currentData;
    private Handler mHandler;

    private KlineExtActivity klineActivity;
    private WrapContentHeightViewPager vp;

    public DealPriceFragment() {
    }

    @SuppressLint("ValidFragment")
    public DealPriceFragment(WrapContentHeightViewPager vp) {
        this.vp = vp;
    }

    @Override
    protected DealPriceFragmentPresenter.DealPriceUI getUI() {
        return this;
    }

    @Override
    protected DealPriceFragmentPresenter createPresenter() {
        return new DealPriceFragmentPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_latest_deal_layout, null, false);
        vp.setObjectForPosition(rootView,1);
        return rootView;
    }

    @Override
    protected void initViews() {
        super.initViews();
        klineActivity = (KlineExtActivity) getActivity();

        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        swipeRefresh.setEnabled(false);
        recyclerView = viewFinder.find(R.id.recyclerView);

        /*viewFinder.textView(R.id.title_buy_amount).setText(String.format(getString(R.string.string_amount_buy_ph), klineActivity.baseTokenName));
        viewFinder.textView(R.id.title_sell_amount).setText(String.format(getString(R.string.string_amount_sell_ph), klineActivity.baseTokenName));
        viewFinder.textView(R.id.title_price).setText(String.format(getString(R.string.string_price_ph), klineActivity.quoteTokenName));*/
        viewFinder.textView(R.id.title_deal_price).setText(String.format(getString(R.string.string_price_ph), klineActivity.quoteTokenName));
        viewFinder.textView(R.id.title_deal_amount).setText(String.format(getString(R.string.string_deal_amount_format), klineActivity.baseTokenName));
//        initData();
//        Bundle arguments = getArguments();
//        if (arguments != null) {
//            String symbol = arguments.getString(AppData.INTENT.SYMBOLS);
//            exchangeId = arguments.getString(AppData.INTENT.EXCHANGE_ID);
//            String mergeDigitsStr = arguments.getString(AppData.INTENT.MERGE_DIGITS);
//            getPresenter().getLatestDeal(exchangeId, symbol);
//        }

        Bundle arguments = getArguments();
        if (arguments != null) {
            coinPairBean = (CoinPairBean)arguments.getSerializable(AppData.INTENT.SYMBOLS);
            if (coinPairBean != null) {
                symbol = coinPairBean.getSymbolId();
                baseToken = coinPairBean.getBaseTokenId();
                quoteToken = coinPairBean.getQuoteTokenId();
                exchangeId = coinPairBean.getExchangeId();
                mergeDigitsStr = coinPairBean.getDigitMerge();
                basePrecision = coinPairBean.getBasePrecision();
                quotePrecision = coinPairBean.getQuotePrecision();
                digitBase = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(symbol+baseToken);
                digitQuote = SymbolDataManager.GetInstance().getTokenDigitBySymbolIdAndTokenId(symbol+quoteToken);
            } else {
                DebugLog.w(TAG,"币对参数异常");
            }
        }

        //合约
        if(KlineUtils.isSymbolOfFutures(coinPairBean.getCoinType()) || KlineUtils.isSymbolOfOption(coinPairBean.getCoinType())){
            viewFinder.textView(R.id.title_deal_amount).setText(String.format(getString(R.string.string_deal_amount_format), getString(R.string.string_option_unit)));
        }

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case REFRESH_DATA:
                        if (currentData != null) {
                            showDataView(currentData);
                        }
                        break;
                }

            }
        };
    }

    private void showDataView(List<DealPriceBean.DealItem> items) {
        DebugLog.d("DealPriceFragment==>:","items=="+items.size());
        currentData = items;
        if (System.currentTimeMillis() - lastUpdateTime < 300) {
            mHandler.removeMessages(REFRESH_DATA);
            mHandler.sendEmptyMessageDelayed(REFRESH_DATA,300);
            return;
        }
        lastUpdateTime = System.currentTimeMillis();

        if (adapter == null) {

            adapter = new DealPriceAdapter(items);
//            adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
            adapter.isFirstOnly(false);
//            adapter.setOnLoadMoreListener(this);

//            swipeRefresh.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
//            swipeRefresh.setOnRefreshListener(this);
            MyLinearLayoutManager lm = new MyLinearLayoutManager(getActivity());
            lm.setOrientation(MyLinearLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(lm);
            lm.setScrollEnabled(false);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.setNewData(items);
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();

    }

    @Override
    public void onLoadMoreRequested() {
        swipeRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                adapter.loadMoreComplete();
            }
        }, 500);
    }

    @Override
    public void onRefresh() {
        setRefreshing(false);
    }


    public void setRefreshing(final boolean refreshing) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refreshing);
            }
        });
    }

    @Override
    public void showLatestDeal(DealPriceBean response) {
        List<DealPriceBean.DealItem> datas = response.getArray();
        if (datas != null) {
            showDataView(datas);
        }
    }

    @Override
    public void showLatestDeal(List<DealPriceBean.DealItem> datas) {
        showDataView(datas);
    }

    @Override
    public String getExchangeId() {
        return exchangeId;
    }

    @Override
    public String getSymbols() {
        return symbol;
    }

    private class DealPriceAdapter extends BaseQuickAdapter<DealPriceBean.DealItem,BaseViewHolder> {

        DealPriceAdapter(List<DealPriceBean.DealItem> data) {
            super(R.layout.item_latest_deal_list_layout, data);
        }

        @Override
        protected void convert(final BaseViewHolder baseViewHolder, final DealPriceBean.DealItem itemModel) {
            //yyyy/MM/dd
            baseViewHolder.setText(R.id.item_deal_time, DateUtils.getSimpleTimeFormatS(itemModel.getT(), "HH:mm:ss"));
            baseViewHolder.setText(R.id.item_deal_price, NumberUtils.roundFormatDown(itemModel.getP(),digitQuote));
            boolean isBuy = itemModel.isM();
            baseViewHolder.setText(R.id.item_deal_type, isBuy?getString(R.string.string_purchase):getString(R.string.string_sellout));
            baseViewHolder.setTextColor(R.id.item_deal_type, isBuy ? getResources().getColor(R.color.green) : getResources().getColor(R.color.red));
            baseViewHolder.setText(R.id.item_deal_amount, NumberUtils.roundFormatDown(itemModel.getQ(),digitBase));
            baseViewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    ToastUtils.showShort(itemModel.time+" : "+itemModel.price);

                }
            });
        }
    }
}
